<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: InfoController.php 197 2011-02-18 12:45:33Z beimuaihui $
 */



Loader::loadClass('json');

class Multilang_InfoController extends Baogg_Controller_Action {

	/*
	 * Init
	 */
	function init() {
		global $json;
		$this->initView ();
		$this->view->baseUrl = $this->_request->getBaseUrl ();
		Zend_Loader::loadClass ( 'Info' );
		$this->info = new Info ( );
		Zend_Loader::loadClass ( 'Language' );
		$this->language = new Language ( );
		Zend_Loader::loadClass ( 'DataLang' );
		$this->dataLang = new DataLang("module_permission");
	}

	
	/**
	 * The default action - Table list
	 */
	public function indexAction() {
		global 	$config,$multiLang;
		$session_prefix = getPageName();

		$translate_lang_id = $_SESSION["s_admin_{$session_prefix}_language_id"] ;
		//Get Language List
		if (!$translate_lang_id ) {
			$translate_lang_id =1;
		}
		//$lang_list = $this->language->getAllByState();
		$lang_list = $this->language->getAllUnlessLang();
		if (is_array($lang_list)) {
			foreach ((array)$lang_list as $key => $value) {
				$lang_arr[$lang_list[$key]['language_id']]=$lang_list[$key]['language_name'];
			}
			$_SESSION["s_admin_{$session_prefix}_language_id"] = (int)$lang_list[0]["language_id"]; 
		}


		$dataConfig['multilang_table_id']  	= "#multilang_table_id";
		$dataConfig[$multiLang->translate_table_name]= "description:15";
		$dataConfig[$multiLang->translate_varibles] = "varCount:10@sortable:false";
		$dataConfig[$multiLang->translate_translated_varibles] = "varCount2:10@sortable:false";
		$dataConfig[$multiLang->g_operate] = "action:10@sortable:false";

		Loader::loadClass("ext::grid");
		$grid = new extGrid("data",'','',array('multilang_content_id'),$dataConfig);

		$grid->unRegisterButton($multiLang->g_add);
		$grid->unRegisterButton($multiLang->g_edit);
		$grid->unRegisterButton($multiLang->g_del);

	//$grid->registerButton($multiLang->g_view_all,"checkLang(\""."{$config['web']['baseurl']}multilang/info/content/?\",\"all\")",'','','view-all-icon');

		//$lang_selects = makeSelectList('language_id', $lang_arr, '', ' id="language_id" onChange="changeLanguage(this.value)" ', $translate_lang_id);
		$lang_selects = makeSelectList('language_id', $lang_arr, '',
			'class="grid_select" onchange="searchComboEvent(ext_store,this.value,\'language_id\',0,'.$grid->_limit.');" class="grid_select"', $translate_lang_id);
		$grid->registerTextBox($multiLang->g_language,$lang_selects);
		$grid->gridHeight = 400;
		$grid->checkBox=false;

		//to this->view
		$this->view->grid = $grid;
		$this->view->config = $config;
	}

	/**
     *   Multilang table list data
     */
	function dataAction() {
		$list = $this->info->getList();
		echoJsonData ( $list["rs"], $list["total"] );
		$this->_helper->viewRenderer->setNoRender ();
	}


	/**
	 * The content  action - list translate contents
	 */
	public function contentAction() {
		global 	$config,$multiLang;
        checkLogin($_SESSION['s_admin_user_id']);
        checkPermission($_SESSION['s_admin_role_id']);
		$this->view->config = $config;

		$session_prefix = getPageName();
		$sessionKeyword=$_SESSION["s_admin_{$session_prefix}_content"];
		$tran_multilang_table_id=$_GET["multilang_table_id"];
		$tran_language_id=$_GET["language_id"];

		$this->view->translateAllUrl="{$config['web']['baseurl']}multilang/info/tranpage/?all=1&language_id={$tran_language_id}&multilang_table_id=";


		//grid 
		$dataConfig['key_id']  	= "#key_id";
		$dataConfig['table_id']		= "#table_id";
		$dataConfig[$multiLang->g_content] = "content_en:15";
		$dataConfig[$multiLang->g_translation] = "content_tran:15";
		$dataConfig[$multiLang->translate_table_name] = "description:10";
		$dataConfig[$multiLang->g_updated_time] = "updated_time_en:10";
		$dataConfig[$multiLang->translate_translate_date] = "updated_time_tran:10";

		Loader::loadClass("ext::grid");
		$grid = new extGrid("contentdata/?language_id={$tran_language_id}&multilang_table_id={$tran_multilang_table_id}",'','',array('key_id','table_id'),$dataConfig);

		//language select list
		//$lang_list = $this->language->getAllByState();
		//$lang_list = $this->language->getAllUnlessLang();
		//if (is_array($lang_list)) {
		//    foreach ((array)$lang_list as $key => $value) {
		//        $lang_arr[$lang_list[$key]['language_id']]=$lang_list[$key]['language_name'];
		//    }
		//}

		//$lang_selects = makeSelectList('language_id', $lang_arr, '',
		//    'class="grid_select" onchange="searchComboEvent(ext_store,this.value,\'language_id\',0,'.$grid->_limit.');" class="grid_select"', $translate_lang_id);

		// table name  select
		$module_data=$this->info->getSelect();
		$module_arr['all']=$multiLang->g_all;
		$module_arr+=(array)$module_data;
		$module_selects = makeSelectList('multilang_table_id_post', $module_arr, '', ' class="grid_select"  onchange="searchComboEvent(ext_store,this.value,\'multilang_table_id\',0,'.$grid->_limit.');" class="grid_select" ', $tran_multilang_table_id);

		$grid->unRegisterButton($multiLang->g_add);
		$grid->unRegisterButton($multiLang->g_edit);
		$grid->unRegisterButton($multiLang->g_del);
	//$grid->registerButton($multiLang->g_translate,
		$grid->getPassParam("{$grid->id}_grid","{$config['web']['baseurl']}multilang/info/tranpage/?language_id={$tran_language_id}&multilang_table_id={$tran_multilang_table_id}");// 1,'','translate-icon');
	//$grid->registerButton($multiLang->translate_translate_all,"translateAll();",'','','translate-all-icon');
	//$grid->registerButton($multiLang->g_back,"window.location.href='{$config['web']['baseurl']}multilang/info/';",'','','back-icon');

		$grid->registerTextBox($multiLang->g_keyword,'<input type="text" name="keyword" value="'.$sessionKeyword.'" id="keyword" onkeypress="searchEvent(ext_store,this.value,event,'.$grid->_limit.')" class="grid_search" >');
		$grid->registerTextBox($multiLang->translate_table_name,$module_selects);

		$grid->gridHeight = 400;
		$grid->checkBox=true;

		//to this->view
		$this->view->grid = $grid;
	}

	/**
     *   Content list data  action
     */
	function contentdataAction() {
        checkLogin($_SESSION['s_admin_user_id']);
        checkPermission($_SESSION['s_admin_role_id']);
		$list = $this->info->getContentList();
		echoJsonData ( $list["rs"], $list["total"] );
		$this->_helper->viewRenderer->setNoRender ();
	}

	/**
     *   Translate Page
     */
	function tranpageAction(){
		global $config,$db,$multiLang;
        checkLogin($_SESSION['s_admin_user_id']);
        checkPermission($_SESSION['s_admin_role_id']);
		$module_data=$this->dataLang->getDataLang( "a.module_permission_type=1", "");
		$module_arr=$this->dataLang->getSelects($module_data);
		$this->view->module_selects = makeSelectList('multilang_table_id_post', $module_arr, '', ' class="grid_select""', $multilang_module_id);
		$this->view->contenttype_selects = makeSelectList('content_type[]',$config['global']['g_multilang_contenttype'], '', ' class="grid_select""', 1);

		$language_id=$_GET['language_id'];
		$multilang_table_id_post=$_GET['multilang_table_id'];
		$key_id=$_GET['key_id'];
		$table_id=$_GET['table_id'];
		$this->view->language_id=$language_id;
		$this->view->multilang_table_id_post=$multilang_table_id_post;
		$this->view->key_id=$key_id;
		$this->view->table_id=$table_id;
		$this->view->db=$db;


		if (!empty($language_id)){
				if ($_GET['all']=="1" && !(empty($multilang_table_id_post)) ){
					// if translate all of a table 
					$sql="select t2.content content_en,
								t1.description description,
							   t3.content content_tran,
							   t2.multilang_table_id table_id,
							   t2.key_id key_id,
								t1.description description
						from multilang_info t2
							 left join multilang_info t3 
							 on t2.multilang_table_id =      t3.multilang_table_id 
							 and t3.language_id = 2 
							 and t2.key_id = t3.key_id
						inner join multilang_table t1
							on t1.multilang_table_id = t2.multilang_table_id
						where t2.language_id = 1
						and t2.multilang_table_id={$multilang_table_id_post}

					";

					$stmt='';     $stmt=$db->query($sql);
					$this->view->rs=$stmt->fetchAll();
				}elseif(is_array($key_id) && is_array($table_id) ){
					//translate what you select 
					$viewrs=array();
					foreach($key_id as $id_k=>$id_v){
						$cids=implode(',',$key_id);
						$sql="select t2.content content_en,
								   t2.value value_en,
								   t3.content content_tran,
								   t3.value value_tran,
								   t2.multilang_table_id table_id,
									t2.key_id key_id,
									t1.description description
							from multilang_info t2
								 left join multilang_info t3 
								 on t2.multilang_table_id =      t3.multilang_table_id 
								 and t3.language_id = 2 
								 and t2.key_id = t3.key_id
							 inner join multilang_table t1
							 on t1.multilang_table_id=t2.multilang_table_id
							where t2.language_id = 1
							and t2.multilang_table_id={$table_id[$id_k]}
							and t2.key_id = {$id_v} 
						";
						//echo $sql;
						//exit();
						$stmt='';     $stmt=$db->query($sql);
						$rs=$stmt->fetchAll();
						$viewrs[]=$rs[0];	
					}
					$this->view->rs=$viewrs;
				}else{
					//other				
					//$sql="select t2.content content_en,
					//           t3.content content_tran,
					//           t2.multilang_table_id multilang_table_id,
					//           t2.key_id key_id
					//    from multilang_info t2
					//         left join multilang_info t3 
					//         on t2.multilang_table_id =      t3.multilang_table_id 
					//         and t3.language_id = 2 
					//         and t2.key_id = t3.key_id
					//    where t2.language_id = 1

					//";
					//echo $sql;
					//$stmt='';     $stmt=$db->query($sql);
					//$this->view->rs=$stmt->fetchAll();
					echo $multiLang->g_invalide_request;
				}
		}else{
			echo $multiLang->g_invalide_request;
		}

		//toolbar
		Loader::loadClass('ext::toolbar');
		$this->view->toolbarButton = new extToolBar();
		$this->view->toolbarButton->registerButton ( $multiLang->g_save, "handleForm('adminForm',\"{$config['web']['baseurl']}multilang/info/tranaction\")", 'save-icon' );
		$this->view->toolbarButton->registerButton ( $multiLang->g_cancel, 'parent.dialog.hide()', 'cancel-icon' );
	}

	/**
     *   Translate Action
     */
	function tranactionAction(){
		global $config,$db,$multiLang;
        checkLogin($_SESSION['s_admin_user_id'],1);
        checkPermission($_SESSION['s_admin_role_id'],1);
		if ($_SESSION['s_admin_user_id'])
			$updated_by=$_SESSION['s_admin_user_id'];
		else
			$updated_by=1;

		$var  = array();
		$var2 = array();
		$tmp1 = array();
		$tmp2 = array();
		//Get post's values 
		$language_id=$_POST['language_id'];
		$table_id=$_POST['table_id'];
		$key_id=$_POST['key_id'];
		$content_en=$_POST['content_en'];
		$tran_content=$_POST['tran_content'];
		$have_value=$_POST['have_value'];
		$v_key=$_POST['v_key'];
		$v_value=$_POST['v_value'];
		if ($language_id ){
			foreach ((array)$_POST['tran_content'] as $k=>$v){
				// foreach content
				
				//get values
				if($have_value[$k]){
					$value_temp=array();
					foreach((array)$v_key[$k] as $kk=>$kv){
						$value_temp[]=$kv."::".$v_value[$k][$kk];
					}
					$value_tran=implode("|*|",$value_temp);
				}else{
					$value_tran="";
				}

				
				// foreach contents
				// Check translate content exist
				$checksql="SELECT 
					  count(*) as total 
					FROM
					   multilang_info  
					   INNER JOIN multilang_table 
					   ON (multilang_info.multilang_table_id = multilang_table.multilang_table_id)
					  where multilang_info.language_id={$language_id}
					  and multilang_info.multilang_table_id={$table_id[$k]}
					  and multilang_info.key_id={$key_id[$k]}
				";

				$checkrs=$db->query($checksql)->fetchAll();
				if ($checkrs[0]["total"]>0){
					//Update Translate
					$sql = "update multilang_info 
						set content='{$tran_content[$k]}',	
						value ='{$value_tran}',
						updated_by ='{$updated_by}',
						updated_time='".date('Y-m-d H:i:s')."' ".
						" where multilang_info.language_id={$language_id}
					  and multilang_info.multilang_table_id={$table_id[$k]}
					  and multilang_info.key_id={$key_id[$k]} ;";
					$log_sql.=$sql;
				}else{
					//New Transalte
					$sql = "insert into multilang_info 
						(language_id,multilang_table_id,key_id,content,value,updated_by,updated_time)
						values({$language_id},{$table_id[$k]},{$key_id[$k]},'{$tran_content[$k]}',
							'{$tran_value}','{$updated_by}', '".date('Y-m-d H:i:s')."' )";
					$log_sql.=$sql;
				}
				//echo $sql;
				//exit();
				$rs=$db->query($sql);
				if ($rs){
					$succResult[]=$content_en[$k];
				}
				else{
					$failResult[]=$content_en[$k];
				}

			}
		}

		if(is_array($failResult)){
			array_unique($failResult);
			$fail_str=implode(", ",$failResult);
			$msg .=$multiLang->g_save_fail." :<br >".$fail_str;
			$flag=0;
			$message="Fail to information translate.";
		}else{
			$msg .=$multiLang->g_save_ok." <br >";
			$flag=1;
			$message="Succ to information translate.";
		}
		echo actionMsg($flag, $msg, $fn);
		$this->_helper->viewRenderer->setNoRender ();

		$log=array();
		$log['module_permission_id'] 	= getPermissionId();
		$log['users_id']				= $_SESSION['s_admin_user_id'];
		$log['message']					= $message;
		$log['log_sql']					= $log_sql;
		$log['result']					= $flag;
		$log['log_users_id']			= $_SESSION['s_admin_user_id'];
		//print_r($log);
		insertLog($log);
	}

}
